package ModLayer;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;

/**
 * Based on the adress-boook example in chap. 12 in the Blue J book.
 * @author (FEN) 
 * @version (2010.09.18)
 */

public class BankFileHandler
{
    private String fileName;
    
    public BankFileHandler(String fileName)
    {
        this.fileName= fileName;
    }
    
    public void saveToFile(ArrayList<PersonInformations> personList) throws IOException
    {
        File destination = makeAbsoluteFilename(fileName);
        ObjectOutputStream os = new ObjectOutputStream(
                                new FileOutputStream(destination));
        os.writeObject(personList);
        os.close();
    }
    
    public ArrayList<PersonInformations> readFromFile()
        throws IOException, ClassNotFoundException
    {
        ArrayList<PersonInformations> returnList= new ArrayList<PersonInformations>();
        try {
            File source = new File(fileName);
            ObjectInputStream is = new ObjectInputStream(
                                   new FileInputStream(source));
            returnList = (ArrayList<PersonInformations>) is.readObject();
            is.close();
        }
        catch(Exception e) {
            throw new IOException("Unable to make a valid filename for " +
                                  fileName);
        }
        return returnList;
    }
    
    private File makeAbsoluteFilename(String filename) throws IOException
    {
        try {
            File file = new File(filename);
            if(!file.isAbsolute()) {
                file = new File(filename);
            }
            return file;
        }
        catch(Exception e) {
            throw new IOException("Unable to make a valid filename for " +
                                  filename);
        }
    }
    
    private File getProjectFolder() throws URISyntaxException
    {
        String myClassFile = getClass().getName() + ".class";
        URL url = getClass().getResource(myClassFile);
        return new File(url.toURI()).getParentFile();
    }
}